package com.ljq.yy.data.singlelinkedlist;

/**
 * 单向链表，持有下一引用
 * @author linjq
 *
 */
public class SingleLinkedList implements List {
	
	//最顶节点
	private Node topNode;
	//当前节点
	private Node currentNode;
	private int size;
	
	//构造
	public SingleLinkedList() {
		topNode = new Node();
		currentNode = topNode;
	}
	
	/**
	 * 通过索引获取当前前点
	 * @param i
	 */
	public void index(int i) {
		
		if(i==-1) {
			return;
		}
		
		//如果当前节点，默认从-1开始，有数据是从0开始
		currentNode = topNode.getNext();
		
		//
		int j = 0;
		while(null!=currentNode && j<i) {
			currentNode = currentNode.getNext();
			j++;
		}
		
	}

	@Override
	public void insert(int i, Object o) throws Exception {
		index(--i);
		currentNode.setNext(new Node(o, currentNode.getNext()));
		size++;
	}

	@Override
	public void delete(int i) throws Exception {
		index(--i);
		System.out.println(currentNode.getElement());
		//将当前节点的下一个节点的下一个节点前移，就达到了删除下一节点
		currentNode.setNext(currentNode.getNext().getNext());
		size--;
	}

	@Override
	public Object getData(int i) throws Exception {
		// TODO Auto-generated method stub
		index(i);
		return currentNode.getElement();
	}

	@Override
	public int size() throws Exception {
		return size;
	}

	@Override
	public Node getNode(int i) throws Exception {
		index(i);
		return currentNode;
	}

}
